<template>
    <div>
      <div>
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="管理员ID">
            <el-input v-model="formSearch.admin_id" placeholder="请输入森林ID"></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="formSearch.admin_name" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="用户类型">
            <el-select v-model="formSearch.admin_grade" placeholder="请选择用户类型">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="普通用户" value="1"></el-option>
              <el-option label="会员用户" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchClick">查询</el-button>
            <el-button type="danger" @click="clearClick">清空</el-button>
            <el-button type="success" @click="addClick">添加用户</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
            :data="tableData"
            stripe
            border
            style="width: 100%">
          <el-table-column
              prop="id"
              label="ID"
              sortable
              width="80px">
          </el-table-column>
          <el-table-column
              prop="admin_id"
              label="管理员ID"
              width="120px">
          </el-table-column>
          <el-table-column
              prop="admin_name"
              label="用户名"
              sortable
              width="120px"
          >
          </el-table-column>
          <el-table-column
              prop="admin_pic"
              label="头像"
              width="80px">
            <template slot-scope="scope">
              <el-avatar :src="baseURL+scope.row.admin_pic"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column
              prop="admin_grade"
              label="类型"
              width="100px">
            <template slot-scope="scope">
              <el-tag
                  :type="scope.row.admin_grade === 1 ? 'primary' : 'success'"
                  disable-transitions>{{scope.row.admin_grade === 1?'普通管理' : '超级管理'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="create_time"
              sortable
              label="注册时间"
              width="180px">
          </el-table-column>
          <el-table-column
              prop="user_state"
              label="状态"
              sortable
              width="100px">
            <template slot-scope="scope">
              <StateCircle :state="scope.row.admin_state === 'ONLINE'"></StateCircle>
              {{scope.row.admin_state === 'ONLINE'?'正常' : '关闭'}}
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
          >
            <template slot-scope="scope"  v-if="($store.state.user&&$store.state.user.admin_grade>1)">
              <el-button v-if="scope.row.admin_state === 'ONLINE'" type="warning" plain @click="offlineClick(scope.row.admin_id,'OFFLINE')">拉黑</el-button>
              <el-button v-else type="warning" plain @click="offlineClick(scope.row.admin_id,'ONLINE')">取消拉黑</el-button>
              <el-button type="primary" plain @click="updateClick(scope.row)">编辑</el-button>
              <el-button type="info" plain @click="updatePassClick(scope.row.admin_id)">修改密码</el-button>
              <el-button type="danger" plain @click="deleteClick(scope.row.admin_id)">删除</el-button>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            layout="prev, pager, next"
            :total="total">
        </el-pagination>
      </div>


      <!--        修改框-->
      <el-dialog title="编辑用户" :visible.sync="dialogFormVisible">
        <el-form :model="updateForm" label-position="right" label-width="80px">
          <el-form-item label="森林ID" >
            <el-input v-model="updateForm.admin_id" disabled autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户名" >
            <el-input v-model="updateForm.admin_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="头像" >
            <el-upload
                class="avatar-uploader"
                :action="baseURL+'/api/file/upload'"
                :show-file-list="false"
                :limit="1"
                :headers="headers"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess">
              <img :src="baseURL+updateForm.admin_pic" class="avatar">
            </el-upload>
          </el-form-item>
          <el-form-item label="类型" >
            <el-select v-model="updateForm.admin_grade">
              <el-option label="普通管理" value="1"></el-option>
              <el-option label="超级管理" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" >
            <el-switch
                v-model="updateForm.admin_state === 'ONLINE'"
                active-color="#13ce66"
                inactive-color="#ff4949"
                disabled>
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUserEvent">确 定</el-button>
        </div>
      </el-dialog>

<!--      添加-->
      <el-dialog title="添加管理员"   :visible.sync="addFormVisible">
        <el-form :rules="rules" :model="addForm" label-position="right" ref="ruleForm" label-width="80px">
          <el-form-item label="用户名" prop="admin_name">
            <el-input  v-model="addForm.admin_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="admin_pass">
            <el-input type="password" show-password v-model="addForm.admin_pass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="admin_pic">
            <el-upload
                class="avatar-uploader"
                :action="baseURL+'/api/file/upload'"
                :show-file-list="false"
                :limit="1"
                :headers="headers"
                :before-upload="beforeAvatarUpload"
                :on-success="addAvatarSuccess">
              <img v-if="addForm.admin_pic" :src="baseURL+addForm.admin_pic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="类型" prop="admin_grade">
            <el-select v-model="addForm.admin_grade">
              <el-option label="普通管理" value="1"></el-option>
              <el-option label="超级管理" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserEvent">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import {editAdmin, editAdminPass, addAdmin, getAdminList, getLogin} from '@/request'
import StateCircle from "@/components/StateCircle";

export default {
  name: "adminList",
  data(){
    return {
      headers: {  // 请求头部参数
        Authorization:this.$store.state.token.tokenn,
      },
      tableData:[],
      total:0,
      pagenum:0,
      formSearch:{
        admin_id:null,
        admin_name:null,
        admin_grade:null,
      },
      dialogFormVisible:false,
      addFormVisible:false,
      updateForm:{},
      addForm:{
        admin_name:null,
        admin_pic:null,
        admin_grade:null,
        admin_pass:null
      },
      rules: {
        admin_name: [
          {required: true, message: '请输入用户名', trigger: 'blur'  },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        admin_pass: [
          {required: true, message: '请输入密码', trigger: 'blur'  },
          { min: 3, max: 12, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        admin_pic: [
          {required: true, message: '请选择头像', trigger: 'blur'  }
        ],
        admin_grade:[
          {required: true, message: '请选择管理类型', trigger: 'blur'  },
        ]
      }
    }
  },
  components:{
    StateCircle
  },
  methods:{
    offlineClick(admin_id,admin_state){
      this.$confirm('您将拉黑该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let data=await editAdmin({admin_id,admin_state});
        if(data.code!=200)return this.$message.error(data.message);
        this.$message.success('成功!');
        this.searchClick();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
      async getAdmin(){
          if(this.pagenum*10>this.total)return;
          this.pagenum++;
          this.formSearch['pagenum']=this.pagenum;
          let data=await getAdminList(this.formSearch);
          if(data.code!=200)return this.$message.error(data.message);
          this.tableData=data.data.list;
          this.total=data.data.total;
    },
    searchClick(){
      this.init();
      this.getAdmin();
    },
    init(){
      this. pagenum=0
      this.total=0
    },
    clearClick(){
      this.formSearch={
        admin_id:null,
        admin_name:null,
        admin_grade:null,
      }
      this.init();
      this.getAdmin();
    },
    updateClick(item){
      this.dialogFormVisible=true;
      this.updateForm={
        admin_id:item.admin_id,
        admin_name:item.admin_name,
        admin_pic:item.admin_pic,
        admin_state:item.admin_state,
        admin_grade:item.admin_grade,
      };
    },
    updatePassClick(admin_id){
      if(!(this.$store.state.user&&this.$store.state.user.admin_grade>1))return this.$message.error("您的权限不足！")
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        inputType:"password",
        cancelButtonText: '取消',
        inputPattern: /^[\w+]{3,16}$/,
        inputErrorMessage: '密码格式不正确'
      }).then(async ({ value }) => {
        let data=await editAdminPass({admin_id,admin_pass:value})
        if(data.code!=200)return this.$message.error(data.message);
        this.$message.success('修改成功!');
        this.searchClick();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消更改'
        });
      });
    },
    deleteClick(admin_id){
      this.$confirm('您将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data=await editAdmin({admin_id,is_delete:1});
        if(data.code!=200)return this.$message.error(data.message);
        this.$message.success('删除成功!');
        this.searchClick();

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async updateUserEvent(){
      console.log(this.updateForm);
      let data=await editAdmin(this.updateForm);
      if(data.code!=200)return this.$message.error(data.message);
      this.$message.success(data.message);
      this.searchClick();
      this.dialogFormVisible=false;
    },
    addAvatarSuccess(res) {
      if (res.code === 200) {
        this.addForm.admin_pic = res.data.filepath;
      } else {
        this.$message.error(res.message)
      }
    },
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.updateForm.admin_pic = res.data.filepath;
      } else {
        this.$message.error(res.message)
      }
    },
    beforeAvatarUpload(file){
      const isLt1M = file.size / 1024 / 1024
      if (isLt1M > 1) {
        this.$message.error('上传头像图片大小不能超过1MB')
      }
      return isLt1M
    },
    addClick(){
      this.addFormVisible=true;
    },
     addUserEvent(){
       let that=this;
       this.$refs['ruleForm'].validate(async (valid)=>{
         if(!valid){
           return false;
         }
         let data=await addAdmin(that.addForm);
         if(data.code!=200)return this.$message.error(data.message);
         this.$message.success('添加成功!');
         this.addFormVisible=false;
         this.searchClick();
       })
    }
  },
  created() {
    this.getAdmin();
  }
}
</script>

<style scoped>
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>